// pages/SuSong/signIn/signIn.js
import request from '../../../utils/config.js';
import util from '../../../utils/util.js';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ossImgUrL: app.globalData.ossImgUrL,
    address: '',
    nowlatitude: '',
    nowlongitude: '',
    latitude:'',
    longitude:'',
    linkman:'',
    recordDesc:'',
    signList: ['新客户拜访', '回访','上门咨询服务'],//1新客户拜访；2回访；3上门服务
    signReasonId:'none',
    tempFilePaths:[],
    custInfo:{}
  },
  getaddress:function(){
    let _this=this;
    wx.chooseLocation({
      success: function (res) {
        console.log(res)
        _this.setData({
          latitude:res.latitude,
          longitude:res.longitude,
        })
        if (res.address == res.name) {
          _this.setData({
            address: res.address,
          })
        } else {
          _this.setData({
            address: res.address +' '+ res.name,
          })
        }
      }
    })
  },
  getNowAddress:function(){
    let _this=this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        wx.stopPullDownRefresh();
        console.log(res)
        _this.setData({
          nowlatitude: res.latitude,
          nowlongitude: res.longitude,
        })
      },
      fail: function (res) {
        wx.stopPullDownRefresh();
        wx.showModal({
          title: '小程序需要你的允许才能正常使用',
          content: '请点击"去设置"并启用"地理位置",然后确定即可正常使用',
          confirmText: '去设置',
          confirmColor: '#35ca14',
          showCancel:false,
          success: function (res) {
            if (res.confirm) {
              wx.openSetting({
                success: (res) => {
                  _this.getNowAddress()
                }
              })
            }
          }
        })
      }
    })
  },
  camera:function(){
    console.log(this.data.tempFilePaths)
    if (this.data.tempFilePaths.length >= 6) {
      wx.showToast({ title: '上传的照片不能超过6张', icon: 'none', duration: 2000 });
      return;
    }
    let _this = this;
    wx.chooseImage({
      sizeType: [ 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: [ 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        console.log("选择照片=", res);
        //开始上传图片
        _this.startUploadImage(tempFilePaths); 
      }
    })
  },
  startUploadImage: function (tempFilePaths){
    let _this = this;
    let bodyInfo = {
      path: tempFilePaths[0]
    }
    wx.showLoading({ title: ' ', mask: true })
    request.requestUploadImg('images', bodyInfo, (res) => {
      wx.hideLoading()
      console.log("上传图片成功=", res);
      var tempRealImgList = _this.data.tempFilePaths;
      tempRealImgList.push(res.data);
      _this.setData({
        tempFilePaths: tempRealImgList
      });
    }, (res) => {
      wx.hideLoading()
      console.log("上传图片失败=", res);
      wx.showToast({
        title: '上传图片失败',
        icon: 'none',
      })
    })
  },
  delImage:function(e){
    let tempFilePaths = this.data.tempFilePaths;
    let index = e.currentTarget.dataset.index;
    let url = tempFilePaths[index].replace(app.globalData.ossUrlPre, '')
    tempFilePaths.splice(index,1)
    this.setData({ tempFilePaths})
    request.requestMisApi("delete", "ossFileDeletes", { ossUrl:url}, (res) => {
      console.log("suc", res)
    }, (res) => {
      console.log("err", res)
    });
  },
  seeImg:function(e){
    console.log("点击预览照片", e.target.dataset.url);
    var tempUrl = e.target.dataset.url;
    wx.previewImage({
      current: tempUrl, // 当前显示图片的http链接
      urls: [tempUrl] // 需要预览的图片http链接列表
    })
  },
  linkmanInput: function (e) {
    this.setData({
      linkman: e.detail.value
    })
  },
  recordDescInput: function (e) {
    this.setData({
      recordDesc: e.detail.value
    })
  },
  signReason:function(){
    let _this=this;
    wx.showActionSheet({
      itemList: _this.data.signList,
      success: function (res) {
        console.log(res.tapIndex)
        _this.setData({ signReasonId: res.tapIndex})
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  send:function(){
    let { address, nowlatitude, nowlongitude, latitude, longitude, linkman, recordDesc, signList, signReasonId, tempFilePaths, custInfo}=this.data
    if (!nowlatitude|| !nowlongitude){
      wx.showToast({ title: '位置获取失败，请下拉重新获取', icon: 'none'});
      return;
    }
    if (!latitude || !longitude ||!address) {
      wx.showToast({ title: '请选择位置信息', icon: 'none' });
      return;
    }
    // console.log(util.SYT_util.getGreatCircleDistance(nowlatitude, nowlongitude, latitude, longitude))
    if (util.SYT_util.getGreatCircleDistance(nowlatitude, nowlongitude, latitude, longitude)>500){
      wx.showToast({ title: '签到距离过远，请在500米之内进行签到', icon: 'none' });
      return;
    }
    if (!linkman) {
      wx.showToast({ title: '请输入联系人', icon: 'none' });
      return;
    }
    if (signReasonId == 'none') {
      wx.showToast({ title: '请选择签到事件', icon: 'none' });
      return;
    }
    // if (!recordDesc) {
    //   wx.showToast({ title: '请输入备注信息', icon: 'none' });
    //   return;
    // }
    if (tempFilePaths.length==0) {
      wx.showToast({ title: '请上传照片', icon: 'none' });
      return;
    }
    let send={
      "address": address,
      "custId": custInfo.custVo.custId,
      "custName": custInfo.custVo.custName,
      "latitude": latitude,
      "linkman": linkman,
      "longitude": longitude,
      "signReasonId": signReasonId*1+1
    }
    if (recordDesc){
      send.recordDesc = send.recordDesc;
    }
    send.images='';
    tempFilePaths.map((item,index)=>{
      if (index!==0){
        send.images = send.images+"&&"+item
      }else{
        send.images = send.images+item
      }
    })
    console.log(send)
    let _this = this;
    wx.showLoading({ title: ' ', mask: true })
    request.requestMisApi("post", "saleSignRecords", send, (res) => {
      console.log("添加", res)
      if (res.code == '00') {
        wx.hideLoading()
        wx.showToast({
          title: res.msg,
          icon: 'success',
          duration: 2000
        })
        setTimeout(function () {
          wx.navigateBack();
        }, 1000);
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    }, (res) => {
      console.log("获取失败", res)
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      custInfo:app.globalData.custInfo,
      linkman: app.globalData.custInfo.saleVo.linkman
    })
    if (!this.data.nowlatitude || !this.data.nowlongitude){
      this.getNowAddress()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getNowAddress()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {
  
  // }
})